package com.sj.parksdk.fragment.parking;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.ruffian.library.widget.helper.RTextViewHelper;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.carmanage.FragmentCarNumberInput;
import com.sj.parksdk.fragment.pay.FragmentPayResult;
import com.sj.parksdk.fragment.profile.FragmentAvailableCoupons;
import com.sj.parksdk.model.bean.PicPreInfo;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Order_Pics;
import com.sj.parksdk.net.result.databean.Data_PrePayment;
import com.sj.parksdk.net.result.databean.Data_Weipay_Native;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.MRTextView.MRTextView;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.core.PageOption;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.data.DateUtils;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = "扫码缴费", params = {Extras.PARK_PARKLOT_ID})
public class FragmentQrCodePay extends BaseFragment {
    @BindView(R2.id.tv_name)
    TextView tvName;
    @BindView(R2.id.rtv_car_color)
    RTextView rtvCarColor;
    @BindView(R2.id.rll_car_color)
    RLinearLayout rllCarColor;
    @BindView(R2.id.tv_cetificat)
    RTextView tvCetificat;
    @BindView(R2.id.ll_top)
    RelativeLayout llTop;
    @BindView(R2.id.tv_address)
    TextView tvAddress;
    @BindView(R2.id.iv_pic)
    ImageView ivPic;
    @BindView(R2.id.tv_start_time)
    TextView tvStartTime;
    @BindView(R2.id.tv_end_time)
    TextView tvEndTime;
    @BindView(R2.id.tv_length)
    TextView tvLength;
    @BindView(R2.id.tv_price)
    TextView tvPrice;
    @BindView(R2.id.tv_coupons)
    TextView tvCoupons;
    @BindView(R2.id.iv_coupons_next)
    ImageView ivCouponsNext;
    @BindView(R2.id.ll_coupons)
    LinearLayout llCoupons;
    @BindView(R2.id.tv_total)
    TextView tvTotal;
    @BindView(R2.id.bt_pay)
    RTextView btPay;
    @BindView(R2.id.tv_alredy_pay)
    TextView tvAlredyPay;
    @BindView(R2.id.bt_confirm)
    SuperButton btConfirm;
    @BindView(R2.id.rtv_exchange_car)
    MRTextView rtvExchangeCar;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;

    @AutoWired(name = Extras.PARK_PARKLOT_ID)
    long parkLotId;

    private Data_PrePayment currentOrder;

    private DateFormat mDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_qrcode_pay;
    }

    @Override
    protected void initViews() {
        btPay.setVisibility(View.GONE);
        rtvExchangeCar.setVisibility(View.GONE);
        rtvCarColor.setVisibility(View.GONE);
        rllCarColor.setVisibility(View.GONE);
        tvCetificat.setVisibility(View.GONE);
        tvAlredyPay.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        showCarNumberInputDialog();
    }

    private void showCarNumberInputDialog() {
        openPageForResult(FragmentCarNumberInput.class,Extras.REQUEST_CAR_INPUT_CAR_NUMBER);
    }

    @SuppressLint("CheckResult")
    private void queryOrder(String carNumber,long couponsId) {
        llState.showLoading();
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request).prepayment(parkLotId, carNumber, couponsId)).subscribeWith(new TipRequestSubscriber<Data_PrePayment>() {
            @Override
            protected void onSuccess(Data_PrePayment data) {
                queryOrderSuccess(data);
            }

            @Override
            public void onError(ApiException e) {
                llState.showError(StringUtils.isEmpty(e.getMessage())?"加载出错":e.getMessage(),null);
            }
        });
    }

    private void queryOrderSuccess(Data_PrePayment data) {
        currentOrder = data;
        llState.showContent();
        if(data.getServiceFee().compareTo(new BigDecimal("0.00")) != 1){
            btConfirm.setEnabled(false);
            btConfirm.setText("无需支付");
        }else{
            btConfirm.setEnabled(true);
            btConfirm.setText("去支付");
        }
        tvAddress.setText(data.getParkingLotName());
        tvStartTime.setText(DateUtils.millis2String(data.getChargeBeginTime(), mDateFormat));
        tvEndTime.setText(DateUtils.millis2String(DateUtils.getNowMills(), mDateFormat));
        tvLength.setText(data.getParkTime());
        tvTotal.setText("¥ " + data.getPayFee().toString());
        tvPrice.setText(data.getServiceFee().toString());
        if (data.getDiscountFee() == null || data.getDiscountFee().compareTo(new BigDecimal("0")) == 0) {
            if (data.getCoupons() == null || data.getCoupons().size() == 0)tvCoupons.setText( "无可用");
            else tvCoupons.setText( data.getCoupons().size() + "张可用");
        } else {
            tvCoupons.setText( "－ ¥" + data.getDiscountFee().toString());
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (data == null) return;
        if (requestCode == Extras.REQUEST_CAR_INPUT_CAR_NUMBER) updateCarInfo(data);
        else if (requestCode == Extras.REQUEST_COUPONS)updateOrder(data);
    }

    private void updateCarInfo(Intent data) {
        String carNumber = data.getStringExtra(Extras.CAR_NUMBER);
        String carColor = data.getStringExtra(Extras.CAR_COLOR);
        tvName.setText(carNumber);
        if (StringUtils.isEmpty(carColor)) carColor = Dictionary.Car.PlateColor.Unknow;
        String plateColorName = Dictionary.Car.PlateColor.PlateColorNameMap.get(carColor);
        int color = Dictionary.Car.PlateColor.PalteColorMap.get(carColor);
        rtvCarColor.setVisibility(View.VISIBLE);
        rllCarColor.setVisibility(View.VISIBLE);
        rtvCarColor.setText(plateColorName);
        RTextViewHelper rtvColorHelper = rtvCarColor.getHelper();
        rtvColorHelper.setBackgroundColorNormal(ResUtils.getColor(color));
        rtvColorHelper.setBorderWidthNormal(DensityUtils.dp2px(carColor.equals(Dictionary.Car.PlateColor.White) ? 1 : 0));
        rtvColorHelper.setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(carColor) ? R.color.color_3 : R.color.color_white));
        rllCarColor.getHelper().setBorderColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(carColor) ?R.color.color_3:color));
        queryOrder(carNumber,0);
    }

    @OnClick({R2.id.ll_coupons, R2.id.rtv_autopay, R2.id.bt_confirm,R2.id.iv_pic})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.ll_coupons) {
            if (checkLogin()) gotoCoupons(0);
        } else if (id == R.id.rtv_autopay) {
        } else if (id == R.id.bt_confirm) {
            weiPay();
        } else if (id == R.id.iv_pic) {
            queryOrderPic();
        }
    }

    private void queryOrderPic() {
        if(currentOrder == null || StringUtils.isEmpty(currentOrder.getOrderNo())){
            XToastUtils.warning("暂无图片");
            return;
        }
        new MGetRequest(MyNetApi.PARK_ORDER_PICS + currentOrder.getOrderNo() + "/pirtures")
                .user()
                .execute(new TipRequestCallBack<Data_Order_Pics>() {
                    @Override
                    public void onSuccess(Data_Order_Pics response) throws Throwable {
                        showPics(response);
                    }
                });
    }

    private void showPics(Data_Order_Pics response) {
        List<String> pic = new ArrayList<>();
        if(response.getInPirtures()!=null )pic.addAll(response.getInPirtures());
        if(response.getOutPirtures()!=null)pic.addAll(response.getOutPirtures());
        if(pic.size() == 0){
            XToastUtils.warning("暂无图片");
            return;
        }
        List<PicPreInfo> pics = new ArrayList<>();
        for (String url:pic
        ) {
            pics.add(new PicPreInfo(url));
        }
        PreviewBuilder.from(getActivity())
                .setImgs(pics)
                .setCurrentIndex(0)
                .setSingleFling(true)
                .setProgressColor(R.color.app_color_theme_main)
                .setType(PreviewBuilder.IndicatorType.Number)
                .start();

    }

    @SuppressLint("CheckResult")
    private void weiPay() {
        if(currentOrder == null){
            XToastUtils.warning("未查询到订单");
            return;
        }
        if(StringUtils.isEmpty(currentOrder.getTradeNo()) || StringUtils.isEmpty(currentOrder.getSign()) || currentOrder.getTimestamp() == 0){
            XToastUtils.warning("订单支付信息异常");
            return;
        }
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .weipaynative(currentOrder.getTradeNo(), currentOrder.getTimestamp(), currentOrder.getSign()))
                .subscribeWith(new TipRequestSubscriber<Data_Weipay_Native>() {
                    @Override
                    protected void onSuccess(Data_Weipay_Native data) {
                        String weipayurl = data.getCode_url();
                        createQrCode(weipayurl);
                    }
                });
    }

    private void createQrCode(String weipayurl) {
        if (StringUtils.isEmpty(weipayurl)) {
            XToastUtils.error("二维码内容为空");
            return;
        }
        Bitmap QRcode = XQRCode.createQRCodeWithLogo(weipayurl, 400, 400, null);
        if (QRcode == null) {
            XToastUtils.error("生成二维码失败");
            return;
        }
        new SweetAlertDialog(getContext(), SweetAlertDialog.CUSTOM_IMAGE_TYPE)
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setCustomImage(new BitmapDrawable(QRcode))
                .setContentText("使用微信扫码支付")
                .setCancelText("取消")
                .setConfirmText("支付完成")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        popToBack();
                    }
                })
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
//                        popToBack();
                        gotoSuccess();
                    }
                }).show();
    }

    private void gotoSuccess() {
        TokenManager.getInstance().refreshPayState(true);
        PageOption.to(FragmentPayResult.class)
                .putBoolean(Extras.BASE_SUCCESS_TYPE,true)
                .putString(Extras.BASE_TITLE,"扫码缴费")
                .putString(Extras.BASE_CODE,"支付成功")
                .putString(Extras.BASE_TYPE,"前往首页")
                .setAddToBackStack(false)
                .open(this);
    }

    private void gotoCoupons(int position) {
        PageOption.to(FragmentAvailableCoupons.class)
                .putInt(Extras.ORDER_CURRENT, position)
                .openForResult(this, Extras.REQUEST_COUPONS);
    }

    private void updateOrder(Intent data) {
        long id = data.getLongExtra(Extras.BASE_CODE, -1);
        if (id == -1) return;
        queryOrder(tvName.getText().toString(), id);
    }
}
